# encoding=utf-8

import base64
import json
from hashlib import md5

from django.http import HttpResponse, HttpResponseBadRequest, Http404
from django.shortcuts import render
from django.utils.timezone import now
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from recognition.serializers import CODE_WHITE_LIST_SERIALIZERS_DICT
from recognition.utils import to_str
from .models import CodeWhiteList, RegLog


# from .tf.tools.food_demo_gai import Recog


def index(request):
    return render(request, 'index.html')


# reg = Recog()

PARITY_BIT = "aGlzZW5zZSBwYXJpdHkgYml0"


def verify_paras(filename, code, timestamp, sign):
    verify_sign = md5(
        (
            to_str(
                md5(
                    (filename + code + timestamp).encode('utf8')
                ).hexdigest()
            )
            +
            to_str(
                base64.b64decode(PARITY_BIT)
            )
        ).encode('utf8')
    ).hexdigest()

    return sign == verify_sign


def recognize(request):
    # verify
    img_file = request.FILES.get('image')
    code_base64 = request.POST.get("code", None)
    timestamp = request.POST.get("timestamp")
    sign = request.POST.get("sign")

    if not code_base64 or not timestamp or not sign or not img_file:
        return HttpResponseBadRequest("数据格式错误( ⊙ o ⊙ )啊！")

    img_file_names = img_file.name
    code = to_str(base64.b64decode(code_base64))

    # save log
    log = RegLog(code=code, img=img_file)
    log.save()

    # verify
    try:
        code_obj = CodeWhiteList.objects.get(code=code)
        if code_obj.is_block:
            return HttpResponseBadRequest("code 无效")

    except CodeWhiteList.DoesNotExist:
        return HttpResponseBadRequest("code 无效")

    verify_res = verify_paras(img_file_names, code=code, timestamp=timestamp, sign=sign)

    if not verify_res:
        return HttpResponseBadRequest("数据格式错误( ⊙ o ⊙ )啊！")

    # reg
    # res = reg.run_test(image_names)

    r = [
        {
            "x1": "574",
            "y1": "136",
            "food_name": "柑橘",
            "x2": "732",
            "y2": "312"
        },
        {
            "x1": "643",
            "y1": "66",
            "food_name": "香蕉",
            "x2": "998",
            "y2": "379"
        },
        {
            "x1": "1040",
            "y1": "175",
            "food_name": "西红柿",
            "x2": "1185",
            "y2": "313"
        },
        {
            "x1": "12",
            "y1": "158",
            "food_name": "牛油果",
            "x2": "218",
            "y2": "355"
        }
    ]

    res = {img_file_names: r}
    res = json.dumps(res)

    # save log res
    log.res = res
    log.save()

    return HttpResponse(res)


class BaseModelViewSet(ModelViewSet):
    """ 重写ModelViewSet类方法 实现软删除 和 根据不同的请求分发序列化 """

    def get_serializer_class(self):
        try:
            return self.serializer_class[self.action]
        except KeyError:
            raise Http404


class CodeWhiteListViewSet(BaseModelViewSet):
    serializer_class = CODE_WHITE_LIST_SERIALIZERS_DICT

    queryset = CodeWhiteList.objects.all()

    # filter_backends = (
    # django_filters.rest_framework.DjangoFilterBackend, filters.OrderingFilter,
    # filters.SearchFilter)

    filter_fields = None
    search_fields = None
    ordering = None

    lookup_field = 'id'

    @action(methods=['POST', ], detail=True, url_path='change-block-status')
    def change_block_status(self, request, id=None):
        is_block = request.data.get('is_block')
        instance = self.get_object()
        if is_block:
            instance.block_time = now()
        else:
            instance.block_time = None
        instance.is_block = is_block
        instance.save()
        return Response('success')

    def create(self, request, *args, **kwargs):

        is_multi = request.data.get('is_multi', True)

        if is_multi:
            codes = request.data['code'].split('\n')
            for code in codes:
                data = request.data.copy()
                data['code'] = code
                serializer = self.get_serializer(data=data)
                serializer.is_valid(raise_exception=True)
                self.perform_create(serializer)
        else:
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
        return Response('success!')
